package com.flismax.mysms.util;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

public class SmsUtil {

	/**
	 * Insert sms to content provider
	 * 
	 * @param context
	 * @param contentUri
	 * @param sms
	 * @return true if insert successfully, else return false
	 */
	public static boolean insert(Context context, Uri contentUri, Sms sms) {
		try {
			ContentResolver resolver = context.getContentResolver();
			ContentValues values = createContentValue(sms);
			resolver.insert(contentUri, values);
			resolver.notifyChange(contentUri, null);
			values.clear();
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	/**
	 * Insert sms to inbox
	 * 
	 * @param context
	 * @param sms
	 *            Sms object to insert
	 * @return true if insert successfully, else return false
	 */
	public static boolean insert(Context context, Sms sms) {
		try {
			// get content resolver
			ContentResolver resolver = context.getContentResolver();
			// create values contain data of sms
			ContentValues values = createContentValue(sms);
			// insert sms to database
			resolver.insert(Sms.INBOX_CONTENT_URI, values);
			// notify change for inbox
			resolver.notifyChange(Sms.INBOX_CONTENT_URI, null);
			// clear value of ContentValue
			values.clear();
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	/**
	 * Clear all conversations
	 * 
	 * @param context
	 * @return
	 */
	public static boolean clearConversations(Context context) {
		int threadId;
		try {
			// get resolver
			ContentResolver resolver = context.getContentResolver();
			// get cursor data contain all conversation
			Cursor cursor = resolver.query(Sms.CONVERSATIONS_CONTENT_URI, null,
					null, null, Sms.DEFAULT_SORT_ORDER);
			// if cursor is null, we do nothing
			if (!cursor.moveToFirst()) {
				return false;
			}
			// else we delete each conversation
			do {
				// get threadID
				threadId = cursor.getInt(cursor
						.getColumnIndex(Sms.TextBasedSmsColumns.THREAD_ID));
				// if threadID = -1, we continue for other conversation
				if (threadId == -1) {
					continue;
				}

				// else we delete conversation
				resolver.delete(
						Uri.parse("content://sms/conversations" + "/"
								+ threadId), null, null);
			} while (cursor.moveToNext());
			cursor.close();
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	/**
	 * Delete conversations by phone number
	 * 
	 * @param context
	 * @param phoneNumber
	 * @return
	 */
	public static boolean deleteConversations(Context context,
			String phoneNumber) {
		try {
			// get content resolver
			ContentResolver resolver = context.getContentResolver();
			// get threadID of conversation need to remove
			int threadId = getThreadId(context, phoneNumber);

			// check condition, if none conversation, we do nothing
			if (threadId == -1) {
				return false;
			}

			// else we delete conversation with threadId
			resolver.delete(
					Uri.parse("content://sms/conversations" + "/" + threadId),
					null, null);
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	/**
	 * Get thread id of conversation
	 * 
	 * @param context
	 * @param phoneNumber
	 * @return threadId of conversation
	 */
	public static int getThreadId(Context context, String phoneNumber) {
		// init default value -1 to threadId when no conversation corresponding
		// with
		// phone number
		int threadId = -1;
		// get resolver
		ContentResolver resolver = context.getContentResolver();
		// get value from column threadID
		String[] projection = new String[] { Sms.TextBasedSmsColumns.THREAD_ID };
		// filter by address (phone number)
		String selection = Sms.TextBasedSmsColumns.ADDRESS + "='" + phoneNumber
				+ "'";
		// get cursor data
		Cursor cursor = resolver.query(Sms.SMS_CONTENT_URI, projection,
				selection, null, Sms.DEFAULT_SORT_ORDER);
		// if cursor not null, we get value from column threadID
		if (cursor.moveToNext()) {
			threadId = cursor.getInt(0);
		}
		// close cursor
		cursor.close();

		return threadId;
	}

	/**
	 * Create content value for insert content provider sms
	 * 
	 * @param sms
	 * @return true if insert successfully, else return fail
	 */
	public static ContentValues createContentValue(Sms sms) {
		ContentValues values = new ContentValues();
		values.put(Sms.TextBasedSmsColumns.TYPE, sms.getType());

		if (sms.getThreadId() != -1) {
			values.put(Sms.TextBasedSmsColumns.THREAD_ID, sms.getThreadId());
		}

		values.put(Sms.TextBasedSmsColumns.ADDRESS, sms.getAddress());
		values.put(Sms.TextBasedSmsColumns.DATE, sms.getDate());
		values.put(Sms.TextBasedSmsColumns.READ, sms.isRead() ? 1 : 0);
		values.put(Sms.TextBasedSmsColumns.SEEN, sms.isSeen() ? 1 : 0);
		values.put(Sms.TextBasedSmsColumns.STATUS, sms.getStatus());

		values.put(Sms.TextBasedSmsColumns.BODY, sms.getBody());
		if (sms.getSubject().length() > 0) {
			values.put(Sms.TextBasedSmsColumns.SUBJECT, sms.getSubject());
		}
		return values;
	}
}
